package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @title: DishServiceImpl
 * @Author 椎名真白
 * @Date: 2022-04-28 14:56
 * @Version 1.0
 */
@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithDishFlavor(DishDto dishDto) {
        //保存菜品 dish
        this.save(dishDto);
        //得到菜品口味的集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历集合  为菜品id赋值 因为前端为传输 只要在选择后才会得到数据
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        //保存菜品口味数据道菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        //清空所有的口味数据
        queryWrapper.eq("dish_id", dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //添加提交的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void updateByIds(int status, Long[] ids) {
        //QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        for (int i = 0; i < ids.length; i++) {
            //queryWrapper.eq("id", ids[i]);
            Dish dish = this.getById(ids[i]);
            log.info("要修改菜品信息{}", dish);
            dish.setStatus(status);
            this.updateById(dish);
        }
    }
}
